package ministock;

import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ConcurrentMap;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import weibo4j.Weibo;
import weibo4j.WeiboException;

import com.google.code.ministock.Stock;

public class CommentConsumer extends Agent {

	private static final Logger logger = LoggerFactory.getLogger(CommentConsumer.class);
	
	public CommentConsumer(ConcurrentMap<String, List<Subscription>> map, BlockingQueue<Stock> stocks, boolean stopped) {
		super(map,stocks,stopped);
	}

	public void commentOn(Stock stock) {
		Weibo weibo = MyWeibo.getInstance();
		List<Subscription> subscriptions = getSubscriptions(stock.getName());
		String comment = displayStock(stock);
		logger.info(comment);
		for(Subscription sub : subscriptions) {
			try {
				logger.debug("updating status comment for {}", sub.getStatusId());
				weibo.updateComment(comment, sub.getStatusId(), null);
			} catch (WeiboException e) {
				e.printStackTrace();
			}
		}
	}
	
	public static String displayStock(Stock stock) {
		StringBuilder sb = new StringBuilder(stock.getDisplayName());
		sb.append(" 现价").append(stock.getCurrentPrice()).append("\r\n");
		sb.append(" 最高").append(stock.getHighestPriceOfToday());
		sb.append(" 最低").append(stock.getLowestPriceOfToday());
		sb.append(" 昨收").append(stock.getClosingPriceOfPreviousMarketDay());
		sb.append(" 今开").append(stock.getOpeningPriceOfToday());
		sb.append(" 成交").append(stock.getVolume(100)).append("手");
		sb.append(" 成交").append(stock.getTurnOver(10000)).append("万");
		sb.append(" ").append(stock.getDate()).append(" ").append(stock.getTime());
		return sb.toString();
	}

	@Override
	public void run() {
		while (!stopped) {
			try {
				Stock stock = stocks.take();
				commentOn(stock);
			} catch (InterruptedException e) {
				e.printStackTrace(System.out);
				stopped = true;
				break;
			}
		}
	}
}
